#define CHAR_WIDRH 2
#define ROWS 25
#define COLS 80
#include "../include/vga.h"
volatile int current_print_position;

char buffer[1000] = {0};

void print_char(int p, int c);

void init_position() {
     current_print_position = 0xb8000 + CHAR_WIDRH * COLS * (ROWS-1);
      //  current_print_position = 0xb8000;
}

// void current_print_position_to_nextline() {
    // current_print_position+=(160-(current_print_position-0xb8000)%160);
// }

void flushbuffer() {
    int p = 0;
    char * b = buffer;

    while (*b!=0) {
        print_char(current_print_position,*b);
        b++;
        current_print_position++;
        current_print_position++;
        movcursor(24,++p);
    }
    init_position();

}

int countargs(char *p) {
    int argcounts = 0;

    while (1) {
        if (*p == '%') {
            argcounts++;
            p++;
        } else if (*p == 0) {
            break;
        } else {
            p++;
        }
    }
    return argcounts;
}
//please remember every after printk() must call rollup()
void printk(char *prompt, ...) {
    int argcounts = countargs(prompt);
    char ** p=(&prompt);
    int bufferindex = 0;
    while (1) {
        if ((*prompt)==0) {
            buffer[bufferindex] = 0;
            break;
        }else if (*prompt == '%') {
            if (argcounts ==0) {
                buffer[bufferindex] = '%';
                bufferindex++;
                continue;
            }
            prompt++;
            p+=1;
            argcounts--;
            switch (*prompt) {
                case 'd':
                    char b[32];
                    char * bb = b;
                    int pp = *(int *)p;
                    for (int i=0;i<31;i++){
                        *bb = pp%10+'0';
                        bb++;
                        pp=pp/10;
                        if (pp==0) {
                            break;
                        }
                    }
                    *bb=0;
                    char * bbb = b;
                    while (*bbb!=0) {
                        buffer[bufferindex]=*bbb;
                        bbb++;
                        bufferindex++;
                    }
                    break;
                case 's':
                    char *p_bcks =*p;
                    while (*p_bcks!=0) {
                        buffer[bufferindex]=*p_bcks;
                        p_bcks++;
                        bufferindex++;
                    }
                    break;
                case 'c':
                    char *p_bckc = (char* )p;
                    buffer[bufferindex] = *p_bckc;
                    bufferindex++;
                    break;
                default:
                    break;
            }
            prompt++;

        }else {
            buffer[bufferindex] = *prompt;
            prompt++;
            bufferindex++;
        }

    }
    flushbuffer();

}




